#pragma once
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
#include <sys/poll.h>
#include "log.hpp"
#include "Err.hpp"
#include "Sock.hpp"

static const uint16_t default_port = 8888;
static const short default_event = 0;
using type_t = struct pollfd;

class PollServer
{
    static const int N = sizeof(fd_set) * 8;

public:
    PollServer(uint16_t port = default_port) : _port(port)
    {
    }

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        // 初始化接收fd的数组
        fdarray = new pollfd[N];
        for (int i = 0; i < N; i++)
        {
            fdarray[i].fd = default_fd;
            fdarray[i].events = default_event;
            fdarray[i].revents = default_event;
        }
    }

    void Start()
    {
        // 将监听socket插入
        LogMessage(Info, "ready to provide service");
        fdarray[0].fd = _listensock.GetFd();
        fdarray[0].events = POLLIN;
        while (true)
        {
            int n = poll(fdarray, N, -1);
            switch (n)
            {
            case 0:
                LogMessage(Info, "time out, %d: %s", errno, strerror(errno));
                break;
            case -1:
                LogMessage(Warring, "%d: %s", errno, strerror(errno));
                break;
            default:
                LogMessage(Info, "There are %d things ready", n);
                EventHandler();
                break;
            }
        }
    }

    void EventHandler()
    {
        for (int i = 0; i < N; i++)
        {
            int fd = fdarray[i].fd;
            short event = fdarray[i].revents;

            if (fd == -1)
                continue;
            if (fd == _listensock.GetFd() && (event & POLLIN))
            {
                Accept();
            }

            if (fd != _listensock.GetFd() && (event & POLLIN))
            {
                Read(i);
            }
        }
    }

    void Accept()
    {
        std::string client_ip;
        uint16_t client_port;
        int sock = _listensock.Accept(&client_ip, &client_port);

        int pos = 1;
        for (; pos < N; pos++)
        {
            if (fdarray[pos].fd == default_fd)
                break;
        }

        if (pos >= N)
        {
            close(sock);
            LogMessage(Bug, "fdarray is full");
        }
        else
        {
            LogMessage(Info, "new sock fdarray[] -> %d", sock);
            fdarray[pos].fd = sock;
            fdarray[pos].events = POLLIN;
        }
    }

    void Read(int index)
    {
        char buffer[1024];
        int n = read(fdarray[index].fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n - 1] = 0;
            std::cout << "client# " << buffer << std::endl;
        }
        else if (n == 0)
        {
            LogMessage(Info, "client quit..., sock: %d", fdarray[index]);
            fdarray[index].fd = default_fd;
            fdarray[index].events = default_event;
            fdarray[index].revents = default_event;
            close(fdarray[index].fd);
        }
        else
        {
        }
    }

    ~PollServer()
    {
        if(fdarray) delete []fdarray;
    }

private:
    uint16_t _port;
    Sock _listensock;
    type_t *fdarray;
};
